import { useEffect, useState, useRef } from "react"
import { useModel, history } from '@umijs/max'
import CloseTab from "@/layouts/CloseTab"
import { getFirstKey, getMenu, getOpenKeys } from "@/layouts/utils"
import { Modal } from "antd"
import { LOGIN_PAGES } from "@/constants"
import { LoginType } from "@/pages/Login/services"

const getUrlParams = () => {
  const urlParams = new URLSearchParams(history.location.search)
  return Object.fromEntries(urlParams)
}

const useGlobal = () => {
  const { initialState } = useModel('@@initialState')
  const [tabs, setTabs] = useState<Tab[]>([]);
  const [activeTabKey, setActiveTabKey] = useState<string>();
  const [menuOpenKeys, setMenuOpenKeys] = useState<string[]>([]);
  const tabHistoryRef = useRef<string[]>([])
  const tabHistory = tabHistoryRef.current

  const setActiveTab = (tabKey?: string) => {
    setActiveTabKey(tabKey)
    if (tabKey) {
      const index = tabHistory.findIndex(item => item === tabKey)
      if (index > -1) {
        tabHistory.splice(index, 1)
      }
      tabHistory.push(tabKey)
    }
  }

  const getTab = async (pathname: string) => {
    const menu = getMenu(initialState!.menuList, pathname)
    if (sessionStorage.userType === String(LoginType.大客户登录)) {
      return import(`../pages/bigClientPages${menu.component}`)
      .then(res => {
        return {
          label: <CloseTab label={menu.name} tabKey={menu.path} />,
          key: menu.path,
          children: <res.default __key={menu.path} params={getUrlParams()} />,
        }
      })
    } else {
      return import(`../pages${menu.component}`)
      .then(res => {
        return {
          label: <CloseTab label={menu.name} tabKey={menu.path} />,
          key: menu.path,
          children: <res.default __key={menu.path} params={getUrlParams()} />,
        }
      })
    }
  }

  const addTab = (pathname: string) => {
    getTab(pathname).then(tab => {
      setTabs(tabs.concat([tab]))
      setActiveTab(tab.key)
    }).catch(err => {
      console.log('err', err)
    })
  }

  const replaceTab = (pathname: string) => {
    if (sessionStorage.getItem('onTabClick') === 'yes' || sessionStorage.getItem('needRefresh') !== 'yes') {
      sessionStorage.removeItem('onTabClick')
      setActiveTab(pathname)
    } else {
      getTab(pathname).then(tab => {
        const index = tabs.findIndex(it => it.key === tab.key)
        setTabs(tabs.filter(item => tab.key !== item.key))
        setTimeout(() => {
          tabs.splice(index, 1, tab)
          setTabs(tabs.map(it => it))
        }, 20)
        setActiveTab(tab.key)
      }).catch(err => {
        console.log('err', err)
      })
    }
  }

  const removeAll = (openFirstMenu?: boolean) => {
    setTabs([])
    setActiveTab(undefined)
    setMenuOpenKeys([])
    tabHistoryRef.current = []
    if (openFirstMenu) {
      setTimeout(() => {
        history.push('/')
      }, 0)
    }
  }

  const removeTab = (tabKey: string, targetUrl?: string) => {
    sessionStorage.removeItem(`__${tabKey}_title`)
    sessionStorage.removeItem(`__${tabKey}_search`)
    setTabs(tabs.filter(item => item.key !== tabKey))
    if (tabKey === activeTabKey) {
      tabHistory.pop()
      if (targetUrl) {
        setTimeout(() => {
          history.push(targetUrl)
        }, 10)
      } else if (tabHistory.length) {
        const _targetUrl = tabHistory.at(-1)!
        const _search = sessionStorage.getItem(`__${_targetUrl}_search`)
        setTimeout(() => {
          history.push(`${_targetUrl}${_search || ''}`)
        }, 10)
      } else {
        setActiveTabKey(undefined)
      }
    } else {
      tabHistoryRef.current = tabHistory.filter(item => item !== tabKey)
    }
  }

  const closeOther = () => {
    setTabs(tabs.filter(item => item.key === activeTabKey))
  }

  const closeCurrentTab = (targetUrl?: string) => {
    removeTab(activeTabKey!, targetUrl)
  }

  const setTab = (pathname: string) => {
    sessionStorage.setItem(`__${pathname}_search`, history.location.search)
    if (tabs.some(item => item.key === pathname)) {
      replaceTab(pathname)
    } else if (tabs.length > 9) {
      Modal.warn({
        content: '请关闭多余的窗口',
      })
      return
    } else {

      console.log('添加路由')
      addTab(pathname)
    }
    sessionStorage.removeItem('needRefresh')
  }

  useEffect(() => {
    /**
     * model 是全局注册，会先于 layout 执行，此处需要判断 menuList 是否存在
     * 确保用户已经登录，如果未登录会跳转到登录页，登录成功后页面跳转会出发下方
     * 路由监听事件，此时 menuList 为空，会导致报错
     */
    if (!initialState?.menuList.length) return
    /**
     * 监听路由跳转实现 tab 的切换功能
     */
    const unListen = history.listen(({location}) => {
      // 登录页不执行设置页签逻辑
      if (LOGIN_PAGES.includes(location.pathname)) return
      if (location.pathname === '/') {
        setTab(getFirstKey(initialState.menuList).path)
      } else {
        setTab(location.pathname)
      }
    })
  
    return () => {
      unListen()
    }
  }, [tabs, initialState?.menuList])

  useEffect(() => {
    // 初始化执行
    console.log('初始化路由')
    if (initialState?.menuList.length) {
      addTab(history.location.pathname)
      setMenuOpenKeys(getOpenKeys(history.location.pathname))
    }
  }, [initialState?.menuList])

  return {
    tabs, removeTab,
    activeTabKey,
    menuOpenKeys, setMenuOpenKeys,
    closeCurrentTab,
    setActiveTab,
    removeAll, closeOther,
  }
}

export default useGlobal
